import React, { useEffect, useMemo } from 'react'
import { GetServerSideProps } from 'next/types'
import { useRouter } from 'next/router'

import { MomentsPageWrap } from '@/components/pages/moments/styled'
import { getMomentListByPageNum } from '@/api/moment'
import { MomentList } from '@/components/pages/moments'
import { Pagination } from '@/components/Pagination'
import { useAppDispatch, useAppSelector } from '@/app/hooks'
import { selectLikeIds, setLikeIds } from '@/app/reducer/momentSlice'
import { setPageTitle } from '@/utils'
import { AppLayout } from '@/layout'

function MomentsPage({ list, totalPage, currentPage }) {
  const router = useRouter()
  const likeIds = useAppSelector(selectLikeIds)
  const dispatch = useAppDispatch()

  const memoMomentList = useMemo(() => list, [list])
  const changePage = (event, value) => {
    router.push({ pathname: '/moments', query: { page: value } })
  }

  useEffect(() => {
    const localLikeIds = JSON.parse(
      window.localStorage.getItem('likeMomentIds') || '[]'
    )
    dispatch(setLikeIds(localLikeIds))
  }, [dispatch])
  useEffect(() => {
    window.localStorage.setItem('likeMomentIds', JSON.stringify(likeIds))
  }, [likeIds])

  useEffect(() => {
    setPageTitle('瞬间')
  }, [])

  return (
    <AppLayout>
      <MomentsPageWrap>
        <div className="title-main">记录瞬间</div>
        <div className="moment-list-main">
          <MomentList list={memoMomentList} likeIds={likeIds} />
        </div>
        <div className="pagination-main">
          <Pagination
            list={memoMomentList}
            handleChange={changePage}
            pages={totalPage}
            page={currentPage}
          />
        </div>
      </MomentsPageWrap>
    </AppLayout>
  )
}

export const getServerSideProps: GetServerSideProps = async (context) => {
  const { page } = context.query
  const currentPage = Number(page) || 1
  const res = await getMomentListByPageNum('', currentPage)
  const { data } = res
  const { list, totalPage } = data
  return {
    props: {
      list,
      currentPage,
      totalPage,
    },
  }
}

export default MomentsPage
